package com.lc.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description: 阿里云 OSS 工具类
 */

@Component
public class AliOSSUtil {

    //华东1（杭州）
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

    //ACCESS_KEY_ID
    private String accessKeyId = "LTAI5tHTJffodCiYifShxy29";
    //ACCESS_KEY_SECRET
    private String accessKeySecret = "kHxujUBu6mgXYCnLZ2DkLKuhJ8VJaX";

    //Bucket名称
    private String bucketName = "kt-cayj";

    /**
     *  上传文件方法
     */
    public String  uploadFile(MultipartFile multipartFile) throws IOException {
        //获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        //避免文件覆盖（文件名重复）
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"))+multipartFile.getOriginalFilename();

        //上传文件到OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        //关闭ossClient
        ossClient.shutdown();

        //把上传到oss的路径返回
        return url;
    }

}
